package cn.wolfcode.trip.base.controller;

import cn.wolfcode.trip.base.domain.Product;
import cn.wolfcode.trip.base.domain.Strategy;
import cn.wolfcode.trip.base.query.ProductQueryObject;
import cn.wolfcode.trip.base.service.IProductService;
import cn.wolfcode.trip.base.util.JSONResult;
import cn.wolfcode.trip.base.util.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private IProductService productService;

    @RequestMapping("/list")
    public Object list(Model model, @ModelAttribute("qo") ProductQueryObject qo){
        // 如果没有选择状态，默认查询未上架商品
        if(qo.getState() == null){
            qo.setState(Product.STATE_WAIT);
        }

        model.addAttribute("pageInfo",productService.queryProduct(qo));

        return "/product/list";
    }

    // 更新游记状态（提交/拒绝）
    @RequestMapping("/changeState")
    @ResponseBody
    public Object changeState(Long id, Integer state){
        productService.changeState(id, state);
        return new JSONResult();
    }

    // 因为涉及到文件上传，所以要多传一个参数 MultipartFile
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Product entity, MultipartFile img){

        // 先处理上传图片问题
        if(img != null && img.getContentType().startsWith("image") && img.getSize() > 0){
            String url = UploadUtil.upload(img);
            entity.setCoverUrl(url);
        }
        productService.saveOrUpdate(entity);
        return "redirect:/product/list.do";
    }

    //查询单个商品信息
    @RequestMapping("/get")
    @ResponseBody
    public Object getProduct(Long id){
        if (id != null){
            return productService.get(id);
        }
        return null;
    }
}
